package com.ls.rbac.security;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * created by liush on 2025/6/27
 **/


@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        String message = exception.getLocalizedMessage();
        HttpStatus status = HttpStatus.BAD_REQUEST;
        if (exception instanceof AccountExpiredException){
            message="账户过期";
            status=HttpStatus.UNAUTHORIZED;
        }else if (exception instanceof BadCredentialsException){
            message="用户名或密码错误";
            status=HttpStatus.UNAUTHORIZED;
        }else if (exception instanceof CredentialsExpiredException){
            message="密码过期";
            status=HttpStatus.UNAUTHORIZED;
        }else if (exception instanceof DisabledException){
            message="账户被禁用";
            status=HttpStatus.FORBIDDEN;
        }else if (exception instanceof LockedException){
            message="账户被锁定";
            status=HttpStatus.FORBIDDEN;
        }else if (exception instanceof InternalAuthenticationServiceException){
            message="用户不存在";
            status=HttpStatus.UNAUTHORIZED;
        }
        AuthenticationResult result=new AuthenticationResult(null,status.value(),message,null,null);
        String jsonString = JSON.toJSONString(result);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.close();
    }
}
